<template>
	<div class="service-list">
		<Layout>
			<Header class="header">
				<Row>
					<Col :span="24">
					<div>
						<span class="border-left"></span>
						服务列表
					</div>
					</Col>
				</Row>
			</Header>
			<Content class="content">
				<div class="search-box">
					<Row :gutter="16" style="min-width:1024px">
						<Col :span="6">
                            服务名称：
                            <Input v-model="name" placeholder="服务名称" style="width:auto" />
						</Col>

                        <!-- <Col :span="6">
                            服务类型：
                            <Select v-model="type" style="width:100px">
                                <Option :value="1">广告类</Option>
                                <Option :value="2">接单类</Option>
                                <Option :value="''">全部</Option>
                            </Select>
						</Col> -->

						<Col :xs="3" :sm="4" :md="4" :lg="6">
						    <div class="search-btn" @click="getServiceList">查询</div>
						</Col>
					</Row>
				</div>

				<div class="add-service">
					<Row>
						<Col :span="24" class="add-btn-box">
						<div class="add-btn" @click="addService">添加服务</div>
						</Col>
					</Row>
				</div>

				<div class="table-box">
					<el-table :data="tableData" size="mini" style="width: 100%;min-width:940px">
						<!-- <el-table-column
                            type="selection"
                            width="55">
                        </el-table-column> -->
						<el-table-column align="center" prop="id" label="服务ID">
						</el-table-column>
						<el-table-column align="center" prop="name" label="服务名称">
						</el-table-column>
						<el-table-column align="center" label="平台收取服务费比例">
							<template slot-scope="scope">
								<p>{{scope.row.proportion}}%</p>
							</template>
						</el-table-column>
						<el-table-column align="center" label="服务订单超时分钟">
							<template slot-scope="scope">
								<p>{{scope.row.overtime}}分钟</p>
							</template>
						</el-table-column>
                        <!-- <el-table-column align="center" label="服务类型">
							<template slot-scope="scope">
								<p>{{scope.row.type === '1' ? '广告类' : scope.row.type === '2' ? '接单类' : '--'}}</p>
							</template>
						</el-table-column> -->
						<el-table-column align="center" label="优惠券剩余数量">
							<template slot-scope="scope">
								<p>{{scope.row.coupon.length > 0 ? scope.row.coupon[0].count : '0'}}</p>
							</template>
						</el-table-column>

						<el-table-column fixed="right" label="操作" width="200" align="center">
							<template slot-scope="scope">
								<el-button type="text" size="small" :disabled="scope.row.coupon.length > 0" @click="add(scope.row.id,scope.row.name)">添加优惠券</el-button>
								<el-button type="text" size="small" @click="edit(scope.row)">编辑</el-button>
								<el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>

				<div class="page-box">
					<Page :total="total" :page-size="pageSize" show-elevator show-total @on-change="pageChange" />
				</div>

				<!-- 添加优惠券模态框 -->
				<el-dialog title="添加优惠券" :visible.sync="addCoupons" width="30%" :before-close="() => addCoupons = false">
					<Row>
						<Col :span="24">
						    服务名称: &nbsp;&nbsp;{{addCouponsName}}
						</Col>
						<Col :span="24" style="margin-top:20px">
                            满减金额:
                            &nbsp;&nbsp;满&nbsp;&nbsp;<InputNumber :min="1" v-model="addCouponsForm.rule_begin" style="width:100px" />&nbsp;&nbsp;
                            减&nbsp;&nbsp;<InputNumber :min="1" v-model="addCouponsForm.rule_later" style="width:100px" />&nbsp;&nbsp;
						</Col>
						<Col :span="24" style="margin-top:20px">
						    发放数量:&nbsp;&nbsp;
						    <InputNumber :min="1" v-model="addCouponsForm.count" style="width:220px" />
						</Col>
					</Row>
					<span slot="footer" class="dialog-footer">
						<el-button @click="addCoupons = false">取 消</el-button>
						<el-button type="primary" @click="addCouponsSubmit">确 定</el-button>
					</span>
				</el-dialog>

				<!-- 编辑服务模态框 -->
				<el-dialog :title="dialogTitle" :visible.sync="editService" width="40%" :before-close="cancel">
					<Form ref="editServiceForm" :model="editServiceForm" :rules="ruleValidate" :label-width="100" style="width: 60%;margin:auto">
						<FormItem label="服务名称：" prop="name">
							<Input v-model="editServiceForm.name" placeholder="请填写服务名"></Input>
						</FormItem>

						<!-- <FormItem label="服务类型：" prop="type">
							<RadioGroup v-model="editServiceForm.type">
								<Radio label="1">广告类</Radio>
								<Radio label="2">接单类</Radio>
							</RadioGroup>
						</FormItem> -->

						<FormItem label="服务费比例：" prop="proportion" class="ivu-form-item-required">
							<Input v-model="editServiceForm.proportion" placeholder="请填写服务费比例">
                                <span slot="append">%</span>
                            </Input>
						</FormItem>

						<FormItem label="超时分钟：" prop="overtime" class="ivu-form-item-required">
							<Input v-model="editServiceForm.overtime" placeholder="请填写超时分钟">
                                <span slot="append">分钟</span>
                            </Input>
						</FormItem>
						<!-- <FormItem>
                            <Button type="primary" @click="handleSubmit('formValidate')">Submit</Button>
                            <Button @click="handleReset('formValidate')" style="margin-left: 8px">Reset</Button>
                        </FormItem> -->
					</Form>
					<span slot="footer" class="dialog-footer">
						<el-button @click="cancel">取 消</el-button>
						<el-button type="primary" @click="submit">确 定</el-button>
					</span>
				</el-dialog>
			</Content>
			<Footer>
				<p class="copy-right">Copyright © {{host}}, All Rights Reserved.</p>
			</Footer>
		</Layout>
	</div>

</template>

<script>
	import * as api from '@/api/api';
	export default {
		data() {
			const validatePercent = (rule, value, callback) => {
				if (value === '') {
					return callback(new Error('请填写服务费百分比'));
				}
				if (!Number.isInteger(value * 1)) {
					callback(new Error('请填写0~100的数字'));
				} else {
					if (value < 0 || value > 100) {
						callback(new Error('请填写0~100的数字'));
					} else {
						callback();
					}
				}
			};
			const validateTimeout = (rule, value, callback) => {
				if (value === '') {
					return callback(new Error('请填写超时时间'));
				}
				if (!Number.isInteger(value * 1)) {
					callback(new Error('请填写0~60的数字'));
				} else {
					if (value < 0 || value > 60) {
						callback(new Error('请填写0~60的数字'));
					} else {
						callback();
					}
				}
			};
			return {
				host: window.location.host,
				loading: this.$store.state,
                name: '',
                type: '',
				tableData: [], //表格数据
				total: 6, //数据总条数
				pageSize: 10, //每页显示条数
				current_page: 1, //当前页
                addCoupons: false, //添加优惠券模态框控制
                addCouponsForm: {
                    rule_begin: null,
                    rule_later: null,
                    count: '',
                    service_id: ''
                },
                addCouponsName: '',
				editService: false, //编辑服务模态框控制
				editServiceForm: {
					name: '', //编辑服务名称
					type: '2', //编辑服务类型
					proportion: '', //编辑服务服务费百分比
					overtime: '', //编辑服务超时时间
                },
                editId: '',
				ruleValidate: {
					name: [{
						required: true,
						message: '请填写服务名',
						trigger: 'blur'
					}],
					type: [{
						required: true,
						message: '请选择服务类型',
						trigger: 'change'
					}],
					proportion: [{
						validator: validatePercent,
						trigger: 'blur'
					}],
					overtime: [{
						validator: validateTimeout,
						trigger: 'blur'
					}]
				},
				dialogTitle: '', //编辑/添加服务模态框标题
			}
		},
		mounted() {
			this.getServiceList();
		},

		computed: {

		},

		watch: {

		},

		methods: {
            pageChange(current_page) {
                this.current_page = current_page;
                this.getServiceList();
            },
			//获取数据
			getServiceList() {
				let body = {
					model: 'Services',
					offset: this.current_page - 1,
					limit: this.pageSize,
					orderBy: 'id asc',
					condition: {
                        is_delete: 0,
                        id:'0,!='
                    },
                    with: {
                        0: 'coupon'
                    },
					search: {
                        name: this.name,
                        type: this.type
					}
				};
				this.loading.isLoading = true;
				api.getDataList(body).then(res => {
					this.loading.isLoading = false;
					this.total = res.data.data.count * 1;
					this.tableData = res.data.data.data;
				}).catch(err => {
					this.$Notice.error({
						title: '错误',
						desc: '服务器错误：' + err
					});
				});
			},
			//添加优惠券
			add(id,name) {
                this.addCouponsForm = {
                    rule_begin: null,
                    rule_later: null,
                    count: '',
                    service_id: ''
                };
                this.addCoupons = true;
                this.addCouponsForm.service_id = id;
                this.addCouponsName = name;
			},
			//编辑服务
			edit(row) {
				this.dialogTitle = '编辑服务';
				this.editServiceForm = {
                    name: row.name, //编辑服务名称
					type: row.type, //编辑服务类型
					proportion: row.proportion, //编辑服务服务费百分比
					overtime: row.overtime, //编辑服务超时时间
                },
                this.editId = row.id;
                this.editService = true;
			},
			//添加服务
			addService() {
				this.editServiceForm = {
					name: '', //编辑服务名称
					type: '2', //编辑服务类型
					proportion: '', //编辑服务服务费百分比
					overtime: '', //编辑服务超时时间
				};
				this.dialogTitle = '添加服务';
				this.editService = true;
			},
			cancel() {
				this.editService = false;
				this.$refs.editServiceForm.resetFields();
				this.editServiceForm = {
					name: '', //编辑服务名称
					type: '2', //编辑服务类型
					proportion: '', //编辑服务服务费百分比
					overtime: '', //编辑服务超时时间
				};
			},
			submit() {
                this.$refs.editServiceForm.validate((valid) => {
                    if(valid) {
                        if(this.dialogTitle === '添加服务') {
                            let body = {
                                model: 'Services',
                                data: this.editServiceForm
                            }
                            api.createData(body).then(res => {
                                if(res.data.code === 200) {
                                    this.editService = false;
                                    this.loading.isLoading = false;
                                    this.$Message.success('添加成功');
                                    this.$refs.editServiceForm.resetFields();
                                    this.getServiceList();
                                }
                            }).catch(err => {
                                this.loading.isLoading = false;
                                this.$Notice.error({
                                    title: '错误',
                                    desc: '服务器错误,请联系管理员（' + err + '）',
                                });
                            })
                        }else {
                            let body = {
                                model: 'Services',
                                data: this.editServiceForm,
                                update_condition: {
                                    id: this.editId
                                }
                            };
                            this.loading.isLoading = true;
                            api.createData(body).then(res => {
                                if(res.data.code === 200) {
                                    this.editService = false;
                                    this.loading.isLoading = false;
                                    this.$Message.success('保存成功');
                                    this.$refs.editServiceForm.resetFields();
                                    this.getServiceList();
                                }
                            }).catch(err => {
                                this.loading.isLoading = false;
                                this.$Notice.error({
                                    title: '错误',
                                    desc: '服务器错误,请联系管理员（' + err + '）',
                                });
                            })
                        }
                    }
                })
            },
            del(id) {
				this.$confirm('此操作将永久删除该服务, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					let body = {
                        model: "Services",
                        data: {
                            is_delete: 1
                        },
                        update_condition: {
                            id: id
                        }
                    };
                    this.loading.isLoading = true;
                    api.createData(body).then(res => {
                        if(res.data.code === 200) {
                            this.getServiceList();
                            this.$Message.success('删除成功');
                        }else {
                            this.loading.isLoading = false;
                            this.$Notice.error({
                                title: '错误',
                                desc: res.data.msg
                            });
                        }
                    }).catch(err => {
                        this.loading.isLoading = false;
                        this.$Notice.error({
                            title: '错误',
                            desc: '服务器错误,请联系管理员（' + err + '）',
                        });
                    });
                })
            },
            
            //添加优惠券
            addCouponsSubmit() {
                let body = {
                    model: 'Coupons',
                    data: this.addCouponsForm
                };
                this.loading.isLoading = true;
                api.createData(body).then(res => {
                    if(res.data.code === 200) {
                            this.getServiceList();
                            this.$Message.success('添加成功');
                            this.addCoupons = false;
                    }else {
                        this.loading.isLoading = false;
                        this.addCoupons = false;
                        this.$Notice.error({
                            title: '错误',
                            desc: res.data.msg
                        });
                    }
                }).catch(err => {
                    this.loading.isLoading = false;
                    this.$Notice.error({
                        title: '错误',
                        desc: '服务器错误,请联系管理员（' + err + '）',
                    });
                })
            }
		}
	}

</script>


<style lang="less">
	@import '../../assets/styles/constant.less';

	.service-list {
		width: 100%;
		height: 100%;
		overflow-x: hidden;
		overflow-y: auto;
		background-color: #f5f7f9;

		.ivu-layout {
			min-height: 100%;
		}

		.header {
			font-size: 14px;
			line-height: 40px;
			height: 40px !important;
			color: #434343;
			padding: 0 50px;
			background-color: @background;
			border-bottom: 1px solid #ddd;

			.border-left {
				border-left: 5px solid @baseColor;
				margin-right: 4px;
			}
		}

		.content {
			width: 100%;
			min-height: 76%;
			padding: 20px 60px;

			.search-box {
				.search-btn {
					width: 100px;
					height: 32px;
					line-height: 32px;
					text-align: center;
					background-color: @greenColor;
					border-radius: 4px;
					color: #fff;
					cursor: pointer;
				}
			}

			.add-service {
				margin-top: 10px;

				.add-btn-box {
					display: flex;
					justify-content: flex-end;

					.add-btn {
						width: 100px;
						height: 32px;
						line-height: 32px;
						text-align: center;
						background-color: #fff;
						border: 1px solid #ddd;
						border-radius: 4px;
						color: #333;
						cursor: pointer;
					}
				}
			}

			.table-box {
				margin-top: 10px;
				min-width: 100%;

				.el-table th {
					background-color: #eee;
					color: #333;
					font-size: 14px;
				}

				.el-button--text {
					color: @greenColor;
				}
			}

			.page-box {
				height: 50px;
				line-height: 50px;
				text-align: right;
				background-color: #fff;
				padding: 0 20px;
			}
		}

		.copy-right {
			text-align: center;
			color: #aaa;
			font-size: 12px;
		}
	}

</style>
